package com.xiaoyang.eurekaclienta.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @auther XiaoYang
 * @DATE 2023/5/3-17:21
 */
@RestController
public class DiscoveryController {

    @Autowired
    private DiscoveryClient discoveryClient;


    /**
     * 通过应用名称 找到服务的ip和 端口
     * 在java中发http请求
     * @param serviceName 应用名称
     * @return ip和端口
     */
    @GetMapping("/test")
    public String doDiscovery(String serviceName){
        //服务发现：通过服务的应用名 找到服务的具体信息
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        ServiceInstance serviceInstance = instances.get(0);
        String ip = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        //instances.forEach(System.out::println);
        //这里找b的ip和端口
        return ip + ":" + port;

    }



}
